<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8" />
  <title>门票预订</title>
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <script src="/js/vue.js"></script>
  <link type="text/css" rel="stylesheet" href="/css/index.css">
  <script src="/js/index.js"></script>
  <script src="/js/axios.min.js"></script>
  <style>
    body { background:#f5f7fa; }
    .page { max-width: 1120px; margin: 20px auto; }
    .title-row { display:flex; align-items:center; justify-content:space-between; margin-bottom:14px; }
    .title { font-size:16px; font-weight:600; color:#303133; display:flex; align-items:center; }
    .title::before { content:""; width:4px; height:14px; background:#67c23a; border-radius:2px; margin-right:8px; }

    .brief { display:grid; grid-template-columns: 260px 1fr; grid-gap: 16px; }
    .cover { width:100%; height:180px; object-fit:cover; border-radius:6px; background:#fafafa; }
    .kv { color:#606266; margin-bottom:8px; }
    .kv b { color:#303133; margin-right:6px; }

    .oprice { color:#c0c4cc; text-decoration: line-through; }
    .dprice { color:#f56c6c; font-weight:600; }

    .sum { font-size:20px; color:#f56c6c; font-weight:700; }
    .footer-bar { display:flex; align-items:center; justify-content:flex-end; gap:12px; padding:20px 0; }
    .form-item { margin-bottom: 16px; }
    .quantity-control { width: 200px; }
    .total-row { text-align: right; padding:10px 0; border-top:1px dashed #eee; }
  </style>
</head>
<body>
<div id="app" class="page">
  <!-- 顶部 -->
  <div class="title-row">
    <div class="title">门票预订</div>
    <div>
      <el-button size="mini" icon="el-icon-arrow-left" onclick="history.back()">返回</el-button>
    </div>
  </div>

  <!-- 订单卡片（修正地址和电话字段） -->
  <el-card shadow="always" style="margin-bottom:14px;">
    <div class="brief" v-loading="loading">
      <img class="cover" :src="scenic.scover || 'https://img.alicdn.com/imgextra/i3/O1CN01dS4W1i1cJH2cJ6MuU_!!6000000003554-2-tps-1200-800.png'" alt="cover" />
      <div>
        <h2 style="margin:0 0 10px; color:#303133;">{{ scenic.scenicName || '—' }}</h2>
        <!-- 修正地址字段为saddress，电话字段为phone -->
        <div class="kv"><b>地址</b>{{ scenic.saddress || '—' }}</div>
        <div class="kv"><b>电话</b>{{ scenic.phone || '—' }}</div>

        <el-divider></el-divider>

        <div class="kv"><b>门票</b>{{ ticket.ticketName || '—' }}</div>
        <div class="kv">
          <b>价格</b>
          <span class="oprice" v-if="hasOprice">￥{{ fmtMoney(ticket.ticketOprice) }}</span>
          <span style="margin:0 6px;" v-if="hasOprice">/</span>
          <span class="dprice">￥{{ fmtMoney(ticket.ticketDprice) }}</span>
        </div>
        <div class="kv"><b>付款方式</b>
          <el-tag size="mini" type="info">{{ mapPayType(ticket.ticketPtype) }}</el-tag>
        </div>
      </div>
    </div>
  </el-card>

  <!-- 预订信息 -->
  <el-card shadow="always" style="margin-bottom:14px;">
    <div class="title">预订信息</div>
    <el-form :model="form" label-width="100px" ref="bookingForm" :rules="rules">
      <el-form-item label="游玩日期" prop="visitDate">
        <el-date-picker
                v-model="form.visitDate"
                type="date"
                placeholder="选择游玩日期"
                :disabled-date="disabledDate"
                style="width: 100%;"
        ></el-date-picker>
      </el-form-item>

      <el-form-item label="购买数量" prop="quantity">
        <el-input-number
                v-model="form.quantity"
                :min="1"
                :step="1"
                label="数量"
                class="quantity-control"
        ></el-input-number>
      </el-form-item>

      <el-form-item label="总金额">
        <div class="sum">￥{{ fmtMoney(totalPrice) }}</div>
      </el-form-item>
    </el-form>
  </el-card>

  <!-- 游客信息（添加常用游客选择） -->
  <el-card shadow="always" style="margin-bottom:14px;">
    <div class="title">游客信息</div>
    <el-form :model="form" label-width="100px" ref="visitorForm" :rules="visitorRules">
      <!-- 常用游客选择下拉框 -->
      <el-form-item label="常用游客">
        <el-select
                v-model="selectedVisitor"
                placeholder="选择常用游客（可选）"
                @change="onVisitorSelect"
        >
          <el-option
                  v-for="visitor in regularVisitors"
                  :key="visitor.phone"
                  :label="`${visitor.name}（${visitor.phone}）`"
                  :value="visitor"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="游客姓名" prop="visitorName">
        <el-input v-model="form.visitorName" placeholder="填写游客姓名"></el-input>
      </el-form-item>

      <el-form-item label="手机号" prop="visitorPhone">
        <el-input v-model="form.visitorPhone" placeholder="填写游客手机号码"></el-input>
      </el-form-item>

      <el-form-item label="身份证号" prop="idCard">
        <el-input v-model="form.idCard" placeholder="填写游客身份证号码"></el-input>
      </el-form-item>

      <el-button type="primary" @click="addToRegular">添加到常用游客</el-button>
    </el-form>
  </el-card>

  <!-- 取票人信息（自动填充登录用户信息） -->
  <el-card shadow="always" style="margin-bottom:14px;">
    <div class="title">取票人信息</div>
    <el-form :model="form" label-width="100px" ref="contactForm" :rules="contactRules">
      <el-form-item label="取票人姓名" prop="contactName">
        <el-input v-model="form.contactName" placeholder="填写取票人姓名"></el-input>
      </el-form-item>

      <el-form-item label="手机号" prop="contactPhone">
        <el-input v-model="form.contactPhone" placeholder="填写取票人手机号码"></el-input>
      </el-form-item>
    </el-form>
  </el-card>

  <!-- 购买须知 -->
  <el-card shadow="always">
    <div class="title">购买须知</div>
    <div class="form-item">
      <p><b>退票规则：</b> 每张退票费用为￥4.4元。请在使用前1天16点之前退票。</p>
    </div>
    <div class="form-item">
      <p><b>取票方式：</b> 持本人身份证到景区入口换取门票。</p>
    </div>
  </el-card>

  <!-- 提交订单 -->
  <div class="footer-bar">
    <el-button @click="goBack">取消</el-button>
    <el-button type="warning" @click="submitOrder" :loading="submitting">提交订单</el-button>
  </div>
</div>

<script>
  new Vue({
    el: '#app',
    data() {
      return {
        scenicId: null,
        ticketId: null,
        scenic: {},
        ticket: {},
        loading: false,
        submitting: false,
        currentUser: null, // 存储当前登录用户信息
        visitorId: null, // 存储用户ID
        regularVisitors: [], // 常用游客列表
        selectedVisitor: null, // 当前选择的常用游客

        form: {
          visitorName: '',
          visitorPhone: '',
          idCard: '',
          contactName: '',
          contactPhone: '',
          visitDate: '',     // 游玩日期
          quantity: 1        // 购买数量
        },
        // 表单验证规则
        rules: {
          visitDate: [
            { required: true, message: '请选择游玩日期', trigger: 'change' }
          ],
          quantity: [
            { required: true, message: '请填写购买数量', trigger: 'blur' },
            { type: 'number', min: 1, message: '购买数量至少为1', trigger: 'blur' }
          ]
        },
        visitorRules: {
          visitorName: [
            { required: true, message: '请填写游客姓名', trigger: 'blur' }
          ],
          visitorPhone: [
            { required: true, message: '请填写游客手机号', trigger: 'blur' },
            { pattern: /^1[3-9]\d{9}$/, message: '请填写正确的手机号', trigger: 'blur' }
          ],
          idCard: [
            { required: true, message: '请填写身份证号码', trigger: 'blur' },
            { pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: '请填写正确的身份证号码', trigger: 'blur' }
          ]
        },
        contactRules: {
          contactName: [
            { required: true, message: '请填写取票人姓名', trigger: 'blur' }
          ],
          contactPhone: [
            { required: true, message: '请填写取票人手机号', trigger: 'blur' },
            { pattern: /^1[3-9]\d{9}$/, message: '请填写正确的手机号', trigger: 'blur' }
          ]
        }
      };
    },
    computed: {
      hasOprice() {
        return this.ticket.ticketOprice !== null && this.ticket.ticketOprice !== undefined && this.ticket.ticketOprice !== '';
      },
      // 计算总金额
      totalPrice() {
        if (!this.ticket.ticketDprice || !this.form.quantity) return 0;
        return Number(this.ticket.ticketDprice) * this.form.quantity;
      }
    },
    mounted() {
      // 1. 先检查登录状态
      const userInfo = localStorage.getItem('userInfo');
      const cid = localStorage.getItem('cid');
      if (!userInfo || !cid) {
        this.$message.error('请先登录');
        // 跳转到登录页，并携带当前booking页面地址作为回调
        const currentUrl = encodeURIComponent(window.location.href);
        window.location.href = `login.html?redirect=${currentUrl}`;
        return; // 未登录则终止后续逻辑
      }

      // 已登录，解析用户信息供后续使用
      this.currentUser = JSON.parse(userInfo);
      this.visitorId = cid;

      // 2. 加载常用游客列表
      this.loadRegularVisitors();

      // 3. 自动填充取票人信息（若有登录用户信息）
      this.autoFillContactInfo();

      // 2. 再处理原有的景区和门票参数逻辑
      const sp = new URLSearchParams(location.search);
      this.scenicId = sp.get('scenicId');
      this.ticketId = sp.get('ticketId');
      if (!this.scenicId || !this.ticketId) {
        this.$message.error('缺少必要参数 scenicId 或 ticketId');
        return;
      }
      this.init();
    },
    watch: {
      // 监听游客姓名和手机号的变化，自动更新取票人信息
      'form.visitorName': function(newVal) {
        if (newVal && !this.form.contactName) {
          this.form.contactName = newVal;
        }
      },
      'form.visitorPhone': function(newVal) {
        if (newVal && !this.form.contactPhone) {
          this.form.contactPhone = newVal;
        }
      }
    },
    methods: {
      // 加载常用游客列表
      loadRegularVisitors() {
        const storedVisitors = localStorage.getItem('regularVisitors');
        this.regularVisitors = storedVisitors ? JSON.parse(storedVisitors) : [];
      },

      // 选择常用游客后自动填充信息
      onVisitorSelect(visitor) {
        if (visitor) {
          this.form.visitorName = visitor.name;
          this.form.visitorPhone = visitor.phone;
          // 如果常用游客信息中包含身份证号，则也填充
          if (visitor.idCard) {
            this.form.idCard = visitor.idCard;
          }
        }
      },

      // 自动填充取票人信息（使用登录用户信息）
      autoFillContactInfo() {
        if (this.currentUser) {
          // 假设登录用户信息中有姓名和电话字段（根据实际接口返回调整）
          this.form.contactName = this.currentUser.name || '';
          this.form.contactPhone = this.currentUser.phone || '';
        }
      },
      mapPayType(ptype) {
        const map = { '1': '景区支付', '2': '网上支付' };
        return map[ptype] || ptype || '网上支付';
      },
      init() {
        this.loading = true;
        const scenicReq = axios.get('/scenic/queryById', { params: { scenicId: this.scenicId } });
        const ticketReq = axios.get('/ticket/queryById', { params: { ticketId: this.ticketId } });
        Promise.all([scenicReq, ticketReq])
                .then(([sres, tres]) => {
                  if (sres.data && sres.data.code === 200) this.scenic = sres.data.data || {};
                  else this.$message.error((sres.data && sres.data.msg) || '获取景区失败');

                  if (tres.data && tres.data.code === 200) this.ticket = tres.data.data || {};
                  else this.$message.error((tres.data && tres.data.msg) || '获取门票失败');
                })
                .catch(err => this.$message.error('请求失败：' + err.message))
                .finally(() => this.loading = false);
      },
      // 禁用过去的日期和超出门票有效期的日期
      disabledDate(time) {
        // 获取当前日期（当天0点）
        const today = new Date();
        today.setHours(0, 0, 0, 0);
        
        // 如果有门票信息，检查是否超出门票有效期
        if (this.ticket && this.ticket.ticketStartrq && this.ticket.ticketEndrq) {
          const startDate = new Date(this.ticket.ticketStartrq);
          const endDate = new Date(this.ticket.ticketEndrq);
          
          // 将日期设置为当天的开始和结束时间，避免时间部分影响比较
          startDate.setHours(0, 0, 0, 0);
          endDate.setHours(23, 59, 59, 999);
          
          // 取两个限制条件的交集：门票有效期和当天及以后
          const maxStartDate = new Date(Math.max(startDate.getTime(), today.getTime()));
          return time.getTime() < maxStartDate.getTime() || time.getTime() > endDate.getTime();
        }
        
        // 默认情况下，禁用过去的日期
        return time.getTime() < today.getTime();
      },
      // 表单验证
      validateForms() {
        return new Promise((resolve, reject) => {
          this.$refs.bookingForm.validate((valid1) => {
            this.$refs.visitorForm.validate((valid2) => {
              this.$refs.contactForm.validate((valid3) => {
                if (valid1 && valid2 && valid3) {
                  resolve(true);
                } else {
                  reject(false);
                }
              });
            });
          });
        });
      },
      // 生成订单号
      generateOrderNo() {
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const day = String(now.getDate()).padStart(2, '0');
        const hours = String(now.getHours()).padStart(2, '0');
        const minutes = String(now.getMinutes()).padStart(2, '0');
        const seconds = String(now.getSeconds()).padStart(2, '0');
        const random = Math.floor(Math.random() * 1000000).toString().padStart(6, '0');
        return `${year}${month}${day}${hours}${minutes}${seconds}${random}`;
      },
      // 提交订单
      submitOrder() {
        this.validateForms().then(() => {
          // 获取当前登录用户ID（实际项目中应从登录状态获取）
          const visitorId = this.visitorId;
          if (!visitorId) {
            this.$message.error('请先登录');
            return;
          }

          this.submitting = true;
          // 构建订单数据
          const orderData = {
            order: {
              visitorId: Number(visitorId),
              orderNo: this.generateOrderNo(),
              orderYwrq: this.form.visitDate instanceof Date ? 
                         this.form.visitDate.toISOString().split('T')[0] : 
                         this.form.visitDate, // 确保日期格式为 YYYY-MM-DD
              orderPtype: this.ticket.ticketPtype, // 支付方式
              orderCount: this.form.quantity, // 总数量
              orderTprice: this.totalPrice, // 总金额
              orderQpname: this.form.contactName, // 取票人姓名
              orderQprsj: this.form.contactPhone, // 取票人手机
              orderState: '11' // 使用OrderStateEnum中定义的待付款状态码
            },
            orderItemList: [{
              ticketId: Number(this.ticketId),
              quantity: this.form.quantity,
              unitPrice: this.ticket.ticketDprice
            }]
          };

          // 提交订单
          axios.post('/order/insert', orderData)
                  .then(res => {
                    if (res.data && res.data.code === 200) {
                      this.$message.success('订单创建成功！');
                      // 修改这里的跳转逻辑
                      setTimeout(() => {
                        // 跳转到支付页面，传递订单号
                        window.location.href = `pay.html?orderNo=${orderData.order.orderNo}`;
                      }, 1000);
                    } else {
                      this.$message.error(res.data.msg || '订单创建失败');
                    }
                  })
                  .catch(err => {
                    this.$message.error('提交失败：' + err.message);
                  })
                  .finally(() => {
                    this.submitting = false;
                  });
        }).catch(() => {
          this.$message.error('请完善所有必填信息');
        });
      },
      addToRegular() {
        // 简单验证
        if (!this.form.visitorName || !this.form.visitorPhone || !this.form.idCard) {
          this.$message.error('请完善游客信息');
          return;
        }
        // 获取本地存储的常用游客列表
        let regularVisitors = JSON.parse(localStorage.getItem('regularVisitors') || '[]');
        // 去重添加
        const isExist = regularVisitors.some(v => v.phone === this.form.visitorPhone);
        if (!isExist) {
          regularVisitors.push({
            name: this.form.visitorName,
            phone: this.form.visitorPhone,
            idCard: this.form.idCard,
            addTime: new Date().toLocaleString()
          });
          localStorage.setItem('regularVisitors', JSON.stringify(regularVisitors));
          this.$message.success('添加到常用游客成功');
        } else {
          this.$message.warning('该游客已在常用列表中');
        }
      },
      fmtMoney(v) {
        return Number(v).toFixed(2);
      },
      goBack() { history.back(); }
    }
  });
</script>
</body>
</html>